<?php
/*
 * 进云智能生成平台
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
 */
defined('BY_JYA') or exit('error');
$op=trim($_RQ['op']);
$type =$_RQ['type'];
$type = in_array($type, array('image','audio','video')) ? $type : 'image';
$setting = $_AR['upload'][$type];
if($op=='wechat_image'){
	$serverid=trim($_RQ['serverid']);
	if(!$serverid){
		exi('参数错误！','error');
	}
	$url=cfc('account')->get_media($serverid);
	$resp = cfc('http')->ihttp_get($url);
	if (is_error($resp)) {
		exi('提取文件失败, 错误信息: '.$resp['message'],'error');
	}
	if (intval($resp['code']) != 200) {
		exi('提取文件失败, 未找到该资源文件.','error');
	}
	$ext = '';
	if ($type == 'image') {
		switch ($resp['headers']['Content-Type']){
			case 'application/x-jpg':
			case 'image/jpeg':
				$ext = 'jpg';
				break;
			case 'image/png':
				$ext = 'png';
				break;
			case 'image/gif':
				$ext = 'gif';
				break;
			default:
				$result['message'] = '提取资源失败, 资源文件类型错误.';
				die(json_encode($result));
				break;
		}
	}else{
		exi('提取资源失败, 仅支持图片提取.','error');
	}
	if ($setting['limit'] && intval($resp['headers']['Content-Length']) > $setting['limit'] * 1024){
		exi('上传的媒体文件过大.','error');
	}
	if(!$group_id){
		$group_id=($_SESSION['this']=='manage')?-1:-2;
	}
	$filename = cfc('files')->source_save($resp['content'],$type,$ext,$serverid,'',$group_id);
	exi($filename);
}
if($op=='upload'){
	if (empty($_FILES['file']['name'])) {
		$result['message'] = '上传失败, 请选择要上传的文件！';
		die(json_encode($result));
	}
	if ($_FILES['file']['error'] != 0) {
		$result['message'] = '上传失败, 请重试.';
		die(json_encode($result));
	}
	$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
	$ext = strtolower($ext);
	$size = intval($_FILES['file']['size']);
	$originname = $_FILES['file']['name'];
	$md5=md5_file($_FILES['file']['tmp_name']);
	$filename=pdo_getcolumn('core_attachment',array('md5'=>$md5,'uniacid'=>$_SESSION['uniacid']),'attachment');
	if(!$filename){
		$filename = cfc('files')->source_save($_FILES['file']['tmp_name'],$type, $ext,str_replace(strrchr($originname,'.'),'',$originname));
	}
}
if ($op == 'fetch' || $op == 'upload') {
	$info = array(
		'attachment' => $filename,
		'url' => tomedia($filename),
		'is_image' => $type == 'image' ? 1 : 0
	);
	die(json_encode($info));
}
?>